<template>
  <el-drawer v-model="formCtrl.isDrawerOpen" class="cupk2-data-form" :append-to-body="true" :with-header="false"
    size="500px">
    <div class="title">{{ currentFormType.type.title }}权限</div>
    <el-form v-loading="isLoading" :model="form" label-width="auto" ref="ruleFormRef" :disabled="!formCtrl.isAbledForm">
      <el-form-item label="上级:" v-if="isShowform.parentLable">
        {{ parentLable }}
      </el-form-item>
      <el-form-item label="创建时间:" prop="ctime" v-if="isShowform.ctime" :rules="v.getRules(true, 0, 7)">
        <el-input v-model="form.ctime" />
      </el-form-item>
      <el-form-item label="修改时间:" prop="etime" v-if="isShowform.etime" :rules="v.getRules(true, 0, 7)">
        <el-input v-model="form.etime" />
      </el-form-item>
      <el-form-item label="修改用户:" prop="euserkey" v-if="isShowform.euserkey" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.euserkey" />
      </el-form-item>
      <el-form-item label="创建用户:" prop="cuserkey" v-if="isShowform.cuserkey" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.cuserkey" />
      </el-form-item>
      <el-form-item label="名称：" prop="name" v-if="isShowform.name" :rules="v.getRules(true, 0, 128)">
        <el-input v-model="form.name" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="排序:" prop="sortcode" v-if="isShowform.sortcode" :rules="v.getRules(true)">
        <el-input-number v-model="form.sortcode" />
      </el-form-item>
      <el-form-item label="状态：" prop="state" v-if="isShowform.state" :rules="v.getRules(true)">
        <el-select v-model="form.state" placeholder="请选择">
          <el-option label="可用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="父节点:" prop="parentid" v-if="isShowform.parentid" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.parentid" />
      </el-form-item>
      <el-form-item label="索引码：" prop="treecode" v-if="isShowform.treecode" :rules="v.getRules(true, 0, 256)">
        <el-input v-model="form.treecode" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="权限类型：" prop="type" v-if="isShowform.type" :rules="v.getRules(true)">
        <el-select v-model="form.type" placeholder="请选择">
          <el-option label="菜单" value="1" />
          <el-option label="权限" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单关键字：" prop="menukey" v-if="isShowform.menukey" :rules="v.getRules(false, 0, 256)">
        <el-input v-model="form.menukey" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="权限关键字：" prop="actions" v-if="isShowform.actions" :rules="v.getRules(false, 0, 256)">
        <el-input v-model="form.actions" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="作用域:" prop="domain" v-if="isShowform.domain" :rules="v.getRules(true, 0, 32)">
        <el-select v-model="form.domain" placeholder="请选择">
          <el-option label="后台功能" value="FRAME" />
          <el-option label="业务功能" value="APP" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注：" prop="note" v-if="isShowform.note" :rules="v.getRules(false, 0, 256)">
        <el-input v-model="form.note" autosize type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-row class="cupk2-form-button">
          <el-col :span="14">
            <el-button v-if="formCtrl.isShowSubmit" type="primary" @click="onSubmitForm(addData)">提交{{
              currentFormType.type.title }}</el-button>
            <el-switch v-if="formCtrl.isShowRetain" v-model="isRetainForm" size="small" inactive-text="提交后保留表单" />
          </el-col>
          <el-col :span="10" class="cupk2-right">
            <el-button v-if="formCtrl.isShowReset" type="warning" @click="onResetForm">清空</el-button>
            <el-button v-if="formCtrl.isShowSubmit" type="info" plain @click="drawerWinOpen(false)">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script lang="ts" setup>

import { inject, onMounted, reactive, ref, watch } from 'vue';
import v from '@/hook/cupkFormValids';
import cupk2Request from '@/service/remoteRequests/Cupk2Request';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import notice from '@/components/msg/CupkNotice';
import { getCreatType, getUpdateType, getViewType, type FormParam } from '@/types/commons/FormType';
import type { DataResponse } from '@/types/commons/DataResponse';
import type { Emitter, EventType } from 'mitt';
import { PageEvent } from '@/types/commons/PageEvent';
import cupkFormUtils from '@/hook/cupkFormUtils';
const eventBus = inject('eventBus') as Emitter<Record<EventType, unknown>>;
const ruleFormRef = ref()
const isLoading = ref(false);
const isRetainForm = ref(false);
const currentFormType = reactive<FormParam>({ type: getViewType(), id: '', data: {} });
const parentLable = ref('');

const formCtrl = reactive({
  isShowRetain: true,
  isShowSubmit: true,
  isDrawerOpen: false,
  isAbledForm: false,
  isShowReset: true
});


const isShowform = reactive({
  id: true,
  ctime: true,
  etime: true,
  euserkey: true,
  cuserkey: true,
  state: true,
  note: true,
  name: true,
  sortcode: true,
  parentid: true,
  treecode: true,
  type: true,
  actions: true,
  domain: true,
  parentLable: true,
  menukey: true
});


const form = reactive({
  id: '',
  ctime: '',
  etime: '',
  euserkey: '',
  cuserkey: '',
  state: '1',
  note: '',
  name: '',
  sortcode: 1,
  parentid: '',
  treecode: '',
  type: '',
  actions: '',
  domain: '',
  menukey: '',
})


watch(
  () => form.type,
  (newVal) => {
    if (newVal == '1') {
      isShowform.menukey = true;
      isShowform.actions = true;
    } else {
      isShowform.menukey = false;
      isShowform.actions = true;
      form.menukey = "";
    }
  }
);


/**
 * 打开或关闭表单窗口
 * @param isOpen
 * @param formType
 */
const drawerWinOpen = (isOpen: boolean, formParam?: FormParam) => {
  if (!isOpen) {
    formCtrl.isDrawerOpen = isOpen;
  } else {
    if (formParam?.type.key !== currentFormType?.type.key) {
      ruleFormRef.value?.resetFields();
    }
    Object.assign(currentFormType, formParam);
    if (formParam?.type.key == getCreatType().key) {
      initCreatForm(formParam);
    }
    if (formParam?.type.key == getUpdateType().key) {
      initUpdateForm(formParam.id);
    }
    if (formParam?.type.key == getViewType().key) {
      initViewForm(formParam.id);
    }
  }
};

/**
 * 初始化创建窗口
 */
const initCreatForm = (formParam: FormParam) => {
  cupkFormUtils.initFormCtrl(getCreatType(), formCtrl);
  Object.assign(isShowform, {
    ctime: false,
    etime: false,
    euserkey: false,
    cuserkey: false,
    state: true,
    note: true,
    name: true,
    sortcode: true,
    parentid: false,
    treecode: false,
    type: true,
    actions: false,
    domain: false,
    menukey: false
  });
  if (formParam) {

    const rowData = formParam?.data as { ID: string, NAME: string };
    if (rowData && rowData.ID) {
      isShowform.parentLable = true;
      form.parentid = rowData.ID;
      parentLable.value = rowData.NAME;
    } else {
      isShowform.parentLable = false;
      form.parentid = "";
    }
  }
}

/**
 * 初始化更新窗口
 * @param id
 */
const initUpdateForm = (id: string | undefined) => {
  cupkFormUtils.initFormCtrl(getUpdateType(), formCtrl);
  if (!id) {
    notice.byError("id不能为空");
  } else {
    isShowform.parentLable = false;
    viewData(id);
    Object.assign(isShowform, {
    ctime: false,
    etime: false,
    euserkey: false,
    cuserkey: false,
    state: true,
    note: true,
    name: true,
    sortcode: true,
    parentid: false,
    treecode: false,
    type: true,
    actions: true,
    domain: false,
    menukey: form.type=='1'
  });
  }
}

/**
 * 初始化浏览窗口
 * @param id
 */
const initViewForm = (id: string | undefined) => {
  cupkFormUtils.initFormCtrl(getViewType(), formCtrl);
  if (!id) {
    notice.byError("id不能为空");
  } else {
    viewData(id);
  }
}

/**
 * 展示信息（加载用户信息）
 */
const viewData = async (id: string) => {
  cupk2Request.submit('api/actions/' + id, RequestTypeEnum.get, isLoading).then((response: DataResponse) => {
    Object.assign(form, response.data)
  }).catch((msg: Error) => {
    notice.byError(msg.message);
  });
}

/**
 * 执行提交按钮（创建/更新）
 */
const addData = async () => {

  if (currentFormType.type.key == getCreatType().key) {
    cupk2Request.submit('api/actions', RequestTypeEnum.post, isLoading, form).then(() => {
      notice.bySuccess("创建成功!");
      eventBus.emit(PageEvent.data_do_query);
      eventBus.emit(PageEvent.data_do_reload_tree_node);
      if (!isRetainForm.value) {
        onResetForm();
        drawerWinOpen(false);
      }
    }).catch((msg: Error) => {
      notice.byError(msg.message);
    });
  }

  if (currentFormType.type.key == getUpdateType().key) {
    cupk2Request.submit('api/actions/' + form.id, RequestTypeEnum.put, isLoading, form).then(() => {
      notice.bySuccess("更新成功!");
      eventBus.emit(PageEvent.data_do_query);
      eventBus.emit(PageEvent.data_do_reload_tree_node);
      onResetForm();
      drawerWinOpen(false);
    }).catch((msg: Error) => {
      notice.byError(msg.message);
    });
  }
}


/**清空表单 */
const onResetForm = () => {
  ruleFormRef.value.resetFields();
}

/**
 * 校验表单，准备提交
 * @param func
 */
const onSubmitForm = async (func: () => void) => {
  await ruleFormRef.value.validate((valid: boolean) => { if (valid) { func() } });
}

onMounted(() => {
  eventBus.on(PageEvent.data_form_open, (paras) => {
    drawerWinOpen((paras as { isOpen: boolean }).isOpen, (paras as { type: FormParam }).type);
  })
});
</script>
